<template>
  <div class="wrap">
    <template>
      <div class="d-flex align-items-center">
        <query-list
                :tipMsg="$t('message.ElementLibrary.pickNoteTip')"
                v-model="selectedList"
                @removeItem="removeSelect"
                :active=1>
        </query-list>
      </div>
      <div class="d-flex align-items-center">
        <label>{{$t('message.ElementLibrary.fileName')}}：</label>
        <el-input v-model="fileName"/>
      </div>
      <!--库列表-->
      <div class="item select-item">
        <!--  要素库-库列表  -->
        <!--        <ElementLibraryLib :selected-item="selectItem"/>-->
        <label>{{$t('message.ElementLibrary.title')}}：</label>
        <el-select class="flex-grow-1" v-model="selectItem" value-key="id" @change="changeSelect">
          <el-option v-for="item in elementLibraryManager.elementLibraryItems"
                     :key="item.id"
                     :label="item.name"
                     :value="item">

          </el-option>
        </el-select>
      </div>
      <!--属性列表-->
      <div class="d-flex align-items-center">
        <label>{{$t('message.ElementLibrary.propertyList')}}：</label>
      </div>
      <div>
        <el-table ref="propertyTable"
                  :data="propertyList"
                  highlight-current-row
                  @current-change="handleCurrentChange"
                  tooltip-effect="dark"
                  style="width: 100%"
                  border size="small"
                  @cell-click="editProperty">
          <el-table-column prop="name"
                           :label="$t('message.ElementLibrary.propertyName')"
                           min-width="100">
            <template v-slot="scope">
              <el-input
                      v-if="scope.row.newAdd && scope.row['nameEdit']"
                      :ref="scope.column.propertyName"
                      v-model="scope.row.name">
              </el-input>
              <span v-else> {{ scope.row.name}} </span>
            </template>
          </el-table-column>
          <el-table-column prop="type"
                           :label="$t('message.ElementLibrary.propertyType')"
                           min-width="100">
            <template v-slot="scope">
              <el-select class="noBorder" v-model="scope.row.type">
                <el-option v-for="(type,index) in propertyType"
                           :key=index
                           :label="type"
                           :value="type">

                </el-option>
              </el-select>
<!--              <el-dropdown trigger="click" @command="changeType($event, scope.row)">-->
<!--                <el-label class="el-dropdown-link" v-model="scope.row.selectType">-->
<!--                  {{ scope.row.selectType }}<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                </el-label>-->
<!--                <el-dropdown-menu slot="dropdown">-->
<!--                  <el-dropdown-item-->
<!--                          v-for="(type,index) in propertyType"-->
<!--                          :key="index"-->
<!--                          :command="type">-->
<!--                    {{ type }}-->
<!--                  </el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--              </el-dropdown>-->
            </template>
          </el-table-column>
          <el-table-column prop="value"
                           :label="$t('message.ElementLibrary.propertyValue')"
                           min-width="100">
            <template v-slot="scope">
              <el-select class="noBorder" v-model="scope.row.selectValue" value-key='value'>
                <el-option v-for="(item,index) in scope.row.value"
                           :key=index
                           :label="item"
                           :value="item">

                </el-option>
                <el-option>
                  <el-button type="text" icon="el-icon-menu" @click="addValue(scope.row)">
                    {{$t('message.ElementLibrary.new')}}
                  </el-button>
                </el-option>
              </el-select>
<!--              <el-dropdown trigger="click" v-if="!scope.row.newAdd" @command="changeValue($event, scope.row)">-->
<!--                <el-label class="el-dropdown-link" v-model="scope.row.selectValue">-->
<!--                  {{ scope.row.selectValue }}<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                </el-label>-->
<!--                <el-dropdown-menu slot="dropdown">-->
<!--                  <el-dropdown-item-->
<!--                          v-for="(item,index) in scope.row.value"-->
<!--                          :key="index"-->
<!--                          :command="item">-->
<!--                    {{ item }}-->
<!--                  </el-dropdown-item>-->
<!--                  <el-dropdown-item>-->
<!--                    <el-button type="text" icon="el-icon-menu" @click="addValue(scope.row)">-->
<!--                      {{$t('message.ElementLibrary.new')}}-->
<!--                    </el-button>-->
<!--                  </el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--              </el-dropdown>-->
<!--              <el-input-->
<!--                      v-else-if="scope.row['valueEdit']"-->
<!--                      :ref="scope.column.propertyValue"-->
<!--                      v-model="scope.row.selectValue">-->
<!--              </el-input>-->
<!--              <span v-else> {{ scope.row.selectValue }} </span>-->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 5px;">
        <el-button type="primary" size="small" @click="addProperty">
          {{ $t('message.ElementLibrary.new') }}
        </el-button>
        <el-button type="primary" size="small" @click="deleteProperty">
          {{ $t('message.ElementLibrary.delete') }}
        </el-button>
        <el-button type="primary" size="small" @click="savePropertyList">
          {{ $t('message.Common.save') }}
        </el-button>
      </div>
      <!--参数化-->
      <div class="d-flex align-items-center">
        <el-checkbox class="el-form-item__label" v-if="allowParam" v-model="isParametric">
          {{$t('message.ElementLibrary.parametric')}}
        </el-checkbox>
      </div>
      <!--参数设置-->
      <div class="height: 238px;" v-if="!loading && isParametric">
        <show-table :datum="datum"
                    :showTab="false"
                    :enable-freeze="false"
                    :editable="true"
                    :validate-field="variableFiledNames"
                    :is-empty-col-names="variableFiledNames"
                    :cell-validate="checkContentIsNumber"
                    height="205px"
                    :show-operation-btn="true"
                    ref="showTable"
                    selected-mode="cell"
                    :excel-import="true"
                    header-align="center"
                    :fill-mode="true"
                    width="100%">
        </show-table>
      </div>
    </template>
    <div class="btn">
      <el-button type="primary" :disabled="selectedList.length === 0" size="small" @click="confirm">
        {{ $t('message.Common.confirm') }}
      </el-button>
      <el-button size="small" @click="close">
        {{ $t('message.Common.close') }}
      </el-button>
    </div>
  </div>
</template>

<script>
  import DialogMixin from "../DialogMixin";
  import {elementLibraryCmd} from "../../../Command/ElementLibrary/ElementLibraryCommand";
  import ElementLibraryLib from "./ElementLibraryLib.vue";
  import {language} from "../../../util/Language";
  import {LibraryItem, LibraryModelType, LibraryType} from "./js/ElementLibraryTypes";
  import elementLibraryManager from "./js/ElementLibraryManager";

  export default {
    components: {ElementLibraryLib},
    mixins: [DialogMixin],
    name: "AddToElementLibraryDlg",
    data() {
      return {
        elementLibraryManager,
        fileName: '',
        selectItem: null,
        loading: true,
        datum: [],
        variableFiledNames: [],
        variableList: [],
        isParametric: false,
        modelType: "",
        addMode: false,
        selectedList: [],//拾取的文档及草图
        propertyList: [],
        propertyType: ["文本","数值"],
        chooseItemIndex: -1,
        currentRow: null,
        allowParam: false,
        deleteProperties: [],
      }
    },
    methods: {
      changePluginContainerHeight() {
        elementLibraryCmd.changePluginContainerHeight({minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight, width: 450})
      },
      init() {
        this.addMode = true;
        elementLibraryManager.initElementLibrary(items => {
          if (items && items.length > 0) {
            this.selectItem = items[0];
          }
          let params = {
            cmdName: 'initData',
            libraryId: this.selectItem?.id,
          }
          elementLibraryCmd.executeElementLibraryCommand(params, res => {
            if (res.variableList.length > 0) {
              this.allowParam = true;
            }
            this.variableFiledNames = Object.keys(res.variableInfo);
            this.datum.push(res.variableInfo);
            this.variableList = res.variableList;
            // this.documentId = res.documentId;
            // this.fileName = res.documentName;
            if (res.modelType === "PartDocument") {
              this.modelType = LibraryModelType.Part;
            } else {
              this.modelType = LibraryModelType.Assembly;
            }
            this.loading = false;
            this.getPropertiesByLibraryId();
          })
        });
      },
      changeSelect() {
        if (!this.selectItem) {
          return;
        }
        this.getPropertiesByLibraryId();
      },
      removeSelect() {
        this.selectedList.splice(0);
      },

      addValue(row) {
        this.$prompt("请输入属性值", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputValidator: (value) => {
            if (!value) {
              return "请输入内容";
            }
            if (row.value?.includes(value)) {
              return "类别名称相同，请重新输入";
            }
          }
        }).then(({value}) => {
          row.selectValue = value;
          row?.value.push(value);
        })
      },
      changeType(type, row) {
        row.selectType = type;
      },
      changeValue(event, row) {
        row.selectValue = event;
        this.$forceUpdate();
      },

      //选中属性一行的时候执行
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      addProperty() {
        this.propertyList.push({
          name:"",
          value: [],
          type: this.propertyType[0],
          selectValue: "",
          newAdd: true,
        })
      },
      deleteProperty() {
        if (!this.currentRow) {
          return;
        }
        this.deleteProperties.push({
          name: this.currentRow.name,
          type: this.currentRow.type,
          value: this.currentRow.value,
          libraryName: this.selectItem?.name,
        })
        let index = this.propertyList.indexOf(this.currentRow);
        this.propertyList.splice(index, 1);
      },
      editProperty(row, column) {
        this.propertyList.forEach(property => {
          property['nameEdit'] = false;
          property['valueEdit'] = false;
        })
        if (column.label === language.getMessage('message.ElementLibrary.propertyName')) {
          //这里是点击让el-input显示
          row['nameEdit'] = true;
          this.$nextTick(() => {
            this.$refs[column.propertyName] && this.$refs[column.propertyName].focus()
          })
        } else if (column.label === language.getMessage('message.ElementLibrary.propertyValue')) {
          row['valueEdit'] = true;
          this.$nextTick(() => {
            this.$refs[column.propertyValue] && this.$refs[column.propertyValue].focus()
          })
        }
      },
      savePropertyList() {
        //需要保存到数据库的新增属性
        let saveProperties = [];
        this.propertyList.forEach(data => {
          if (data.name) {
            saveProperties.push({
              name: data.name,
              type: data.type,
              value: data.value,
              libraryName: this.selectItem?.name,
            })
          }
        })

        let param = {
          cmdName: "modifyElementLibraryProperty",
          saveProperties: saveProperties,
          deleteProperties: this.deleteProperties,
        }

        elementLibraryCmd.executeElementLibraryCommand(param, res => {})
        this.deleteProperties = [];
      },
      confirm() {
        if (this.selectedList.length <= 0) {
          elementLibraryCmd.eventBusAlertMsg(this.$t('message.ElementLibrary.pickNoteTip'), "warning");
          return;
        }
        if (!this.fileName) {
          elementLibraryCmd.eventBusAlertMsg("请输入文件名称！", "warning");
          return;
        }
        // 如果是参数话构建的话
        // 参数化构件
        let paramList = [];
        if (this.isParametric) {
          this.variableList.forEach((variable, index) => {
            paramList.push({
              name: variable.fullName,
              variableType: variable.variableType,
              variableUnit: variable.variableUnit,
              defaultValue: variable.variableValue,
              expression: variable.expression,
              variableDescription: variable.variableDescription,
              instanceIds: variable.instanceIds,
              topVariable: variable.topVariable,
              docId: variable.docId,
            });
          });
        }
        //需要保存的新增的类别
        // let saveCategoryData = this.categoryList.filter(data => data.newAdd === true && delete data.newAdd);
        // let firstCategoryList = [];
        // let secondCategoryList = [];
        // let thirdCategoryList = [];
        // this.tableData.forEach(row => {
        //   firstCategoryList.push(row.firstCategoryList.filter(classObject => (classObject.newAdd === true && delete classObject.newAdd)));
        //   secondCategoryList.push(row.secondCategoryList.filter(classObject => (classObject.newAdd === true && delete classObject.newAdd)));
        //   thirdCategoryList.push(row.thirdCategoryList.filter(classObject => (classObject.newAdd === true && delete classObject.newAdd)));
        // });
        // let saveCategoryMap = {
        //   level1: firstCategoryList,
        //   level2: secondCategoryList,
        //   level3: thirdCategoryList,
        // };
        //当前选择的要素库的属性分类
        let properties = [];
        this.propertyList.forEach(data => {
          let tempValue = {
            name: data.name,
            type: data.type,
            value: data.selectValue,
          };
          properties.push(tempValue);
        })

        let config = {
          modelType: this.modelType,
          isParametric: this.isParametric,
        }
        //要素库ID
        let itemId = this.selectItem?.id;
        //选择对象的类型
        let objId = this.selectedList[0]?.id;
        let objType = this.selectedList[0]?.type === "Sketch" ? LibraryType.SKETCH : LibraryType.MODEL;

        let paramA = {
          cmdName: "saveData",
          fileName: this.fileName,
          datum: this.datum,
          libraryId: itemId,
          objType: objType,
          objId: objId,
          config: config,
          paramList: paramList,
          properties: properties,
        }

        elementLibraryCmd.executeElementLibraryCommand(paramA, res => {
          // config["templateId"] = res.templateId;
          // config["parametricTableId"] = res.parametricTableId;
          // let item = elementLibraryManager.buildItem(this.fileName, itemId, LibraryType.MODEL, false, JSON.stringify(config));
          // item.setThumbnail(res.thumbnail);
          elementLibraryManager.addAppendChildren(itemId, new LibraryItem(res));
        })
      },
      close() {
        elementLibraryCmd.closeActiveCmd();
      },
      checkContentIsNumber(content) {
        let result = {
          validateResult: true,
          message: ''
        };
        let isNumberRegx = /^\d*(\.)*\d*$/;
        let isNumber = isNumberRegx.test(content);
        if (!isNumber) {
          result.validateResult = false;
          result.message = language.getMessage('message.ElementLibrary.inputNumber');
        }

        return result;
      },
      getPropertiesByLibraryId() {
        this.propertyList.splice(0);
        let params = {
          cmdName: 'getElementLibraryPropertyByLibraryId',
          libraryId: this.selectItem?.id,
        }
        elementLibraryCmd.executeElementLibraryCommand(params, data => {
          data?.forEach(prop => {
            let tempProperty = this.propertyList.filter(value => value.name === prop.name);
            if (tempProperty.length === 0) {
              this.propertyList.push(prop);
              prop.type = this.propertyType[0];
              if (prop.value && prop.value.length > 0) {
                // prop.selectValue = prop.value[0];
              }
            }
          })
        });
      },
    },
    mounted() {
      elementLibraryCmd.init(600, 500, 500, () => {
        this.init();
        elementLibraryCmd.handleDocumentSelectedEvent(data => {
          this.selectedList.splice(0);
          data?.forEach(obj => {
            this.selectedList.push(obj);
            this.fileName = obj?.name;
          });
        })
        // elementLibraryCmd.handlePickFeatureNode(res => {
        //   this.selectedList.splice(0);
        //   this.selectedList.push(res.feature);
        //   this.fileName = res.feature?.name;
        // });
      });
    },
    computed: {
    }
  }
</script>

<style scoped>
  .wrap {
    font-size: 12px;
  }

  select, input {
    outline: none;
    border: none;
  }

  .item {
    color: var(--text-color1);
    margin: 10px auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .item select, .item input:hover {
    border-bottom: 1px solid var(--border-color5);
  }

  .item input {
    border-bottom: 1px solid var(--border-color3);
  }

  .item select, .item input {
    color: var(--text-color1);
    background-color: transparent;
    width: 150px;
  }

  .item select option {
    color: var(--text-color2);
    background-color: var(--bg-color2);
  }

  input.item {
    outline: none;
    border: none;
    color: var(--text-color1);
    background-color: var(--bg-color1);
    border-bottom: 1px solid var(--border-color3);
    text-align: center;
    height: 22px;
    width: 100%;
  }

  input.item:hover, input.item:focus {
    border-bottom: 1px solid var(--border-color5);
  }

  .select input {
    position: absolute;
    width: 120px;
    left: 3px;
    border-bottom: none;
  }

  .select-item > span {
    text-align: left;
    width: 38px;
  }

  .table-style {
    padding: 2px!important;
  }

  .table-style table {
    color: var(--text-color1)!important;
    font-size: var(--text-14);
    table-layout: fixed;
    width: 100%;
  }

  .table-style td {
    border: 1px solid var(--border-color3);
    font-size: 12px;
  }

  .table-style tr {
    height: 25px;
  }

  .cell-padding {
    padding: 2px!important;
    -webkit-user-select: text;
    -moz-user-select: text;
    user-select: text;
  }

  .tw-font-bold {
    font-weight: 700!important;
  }

  .tw-top-0 {
    top: 0!important;
  }

  .tw-sticky {
    position: sticky!important;
  }

  .tr-bg-color {
    background-color: var(--bg-color1)!important;
  }

  .el-dropdown-link {
    font-size: 12px;
    cursor: pointer;
  }

  .tw-h-full {
    height: 100%!important;
  }

  .tw-w-full {
    width: 100%!important;
  }

  .\!tw-select-text, .tw-select-text {
    -webkit-user-select: text!important;
    -moz-user-select: text!important;
    user-select: text!important;
  }

  .tw-overflow-hidden {
    overflow: hidden!important;
  }

  .tw-overflow-ellipsis, .tw-text-ellipsis {
    text-overflow: ellipsis!important;
  }

  .tw-whitespace-nowrap {
    white-space: nowrap!important;
  }

  .noBorder {
    border: 0 !important;
  }
</style>